package com.bxshey.happyTown.utils;


import com.bxshey.happyTown.entity.User;
import io.jsonwebtoken.*;

import java.util.Calendar;
import java.util.Map;
import java.util.UUID;

/**
 * @作者：不想说话而已
 * @Date：2023/12/10 14:07
 */
public class JwtUtils {

    private static final String KEY = "bxshey";

    //生成token
    public static String createToken(Map<String,String> info){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR,1); //有效期三个小时
        JwtBuilder builder = Jwts.builder();
        return builder
                .setHeaderParam("type","JWT")
                .setHeaderParam("alg","HS256")
                .claim("username",info.get("username"))
                .claim("id",info.get("id"))
                .setSubject("web")
                .setExpiration(calendar.getTime())
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256,KEY)
                .compact();

    }

    //检查token
    public static User checkToken(String token){

        try {
            Jws<Claims> claimsJws;
            claimsJws = Jwts.parser().setSigningKey(KEY).parseClaimsJws(token);
            Claims body = claimsJws.getBody();
            User user = new User();
            user.setId(Integer.valueOf(body.get("id").toString()));
            user.setUsername(String.valueOf(body.get("username")));
            return user;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
}
